package simpleservletcontainer;


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ServletProcessor {

	public void process(Request request, Response response) throws MalformedURLException {
		String uri = request.getUri();
		String servletName = uri.substring(uri.lastIndexOf("/")+1);
		URLClassLoader loader = null;
		
		// 动态加载类
		URL[] urls = new URL[1];
		urls[0] = new URL("file",null,HttpServer.SERVLET_ROOT);
		loader = new URLClassLoader(urls);
		System.out.println(urls[0]);
		Class myClass = null;
		try {
			myClass = loader.loadClass(servletName);
			System.out.println("loaded class");
			// 运行servlet
			try {
				System.out.println("init class");
				Servlet servlet = (Servlet)myClass.newInstance();
				System.out.println("inited class");
				servlet.service((ServletRequest)request,(ServletResponse)response);
				System.out.println("runed class");
			} catch (InstantiationException | IllegalAccessException | ServletException | IOException e) {
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			try {
				PrintWriter out = (PrintWriter)response.getWriter();
				String err = "HTTP/1.1 404 File Not Found\r\n"
						+ "Content-Type: text/html\r\n"
						+ "Content-Length: 23\r\n"
						+ "\r\n"
						+ "<h1>Class Not Found</h1>";
				out.println(err);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}	
}

